package net.zio.kamenriderzioaddon.network;

import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.zio.kamenriderzioaddon.KamenRiderZioAddonMod;
import net.zio.kamenriderzioaddon.ridersystem.data.PlayerDataManager;

/**
 * 玩家变量提供器
 *
 * @author QianYunYi
 */
@Mod.EventBusSubscriber(modid = KamenRiderZioAddonMod.MODID)
public final class AddonPlayerVariablesProvider implements ICapabilitySerializable<CompoundTag> {

    private final PlayerDataManager data;
    private final LazyOptional<PlayerDataManager> instance;

    public AddonPlayerVariablesProvider(Player player) {
        this.data = PlayerDataManager.get(player);
        this.instance = LazyOptional.of(() -> data);
    }

    @SubscribeEvent
    public static void onAttachCapabilities(AttachCapabilitiesEvent<Entity> event) {
        if (event.getObject() instanceof Player && !(event.getObject() instanceof FakePlayer)) {
            event.addCapability(
                    new ResourceLocation(KamenRiderZioAddonMod.MODID, "player_variables"),
                    new AddonPlayerVariablesProvider((Player) event.getObject())
            );
        }
    }

    @Override
    public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
        // 若存在 PlayerDataCapability 再替换
        return cap == null ? instance.cast() : LazyOptional.empty();
    }

    @Override
    public CompoundTag serializeNBT() {
        return data.serializeNBT();
    }

    @Override
    public void deserializeNBT(CompoundTag nbt) {
        data.deserializeNBT(nbt);
    }
}